package components.hystrix;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import rx.Observable;
import rx.functions.Action1;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
* @desc   hystrix demo
 * https://www.iteye.com/blog/hot66hot-2155036
* @author kanggw
* @datetime 2021/9/1,19:43
*/
public class HelloWorldCommand extends HystrixCommand<String> {

    private final String name;

    protected HelloWorldCommand(String name) {
        super(HystrixCommandGroupKey.Factory.asKey(name));
        this.name = name;
    }

    @Override
    protected String run() throws Exception {
         // 依赖逻辑封装在run()方法中
        System.out.println("***run方法执行了********");
        System.out.println("thread name: " +Thread.currentThread().getName());
        return "Hello " + name +" thread:" + Thread.currentThread().getName();

    }

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        //每个Command对象只能调用一次,不可以重复调用,
        //重复调用对应异常信息:This instance can only be executed once. Please instantiate a new instance.

        HelloWorldCommand helloWorldCommand = new HelloWorldCommand("ynchronous-hystrix");
        String result = helloWorldCommand.execute();
        System.out.println("out:" + result);

        //异步调用,可自由控制获取结果时机
        HelloWorldCommand asynchronousResult = new HelloWorldCommand("Asynchronous-hystrix");
        Future<String> queue = asynchronousResult.queue();
        String s = queue.get(10000, TimeUnit.MILLISECONDS);
        System.out.println("Asynchronous out:" + s);

        System.out.println("mainThread=" + Thread.currentThread().getName());

        Observable<String> observe = new HelloWorldCommand("world").observe();

        observe.subscribe(new Action1<String>() {
            @Override
            public void call(String s) {
                System.out.println("action1******");
            }
        });
    }
}
